package cn.tom.service.impl;

import cn.tom.dao.CommentDao;
import cn.tom.entity.Comment;
import cn.tom.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentDao commentDao;
    @Resource
    private RedisTemplate redisTemplate;

    /**
     *  一个商品的多条评论 放一个list
     *   前面 加上 t_comment:  分区
     *  list 名 ：商品ID
     * */
    @PostConstruct
    private void init(){
        ListOperations redisList = redisTemplate.opsForList();
        List<Comment> list = commentDao.findByid(new ManagedMap<>());
        for (Comment comment : list) {
            redisList.leftPush("t_comment:" + comment.getBook().getId()
                            , comment);
        }
    }

    @Override
    public int add(Comment comment) {
        return commentDao.add(comment);
    }

    @Override
    public List<Comment> findByid(Integer bookid, Integer uid, Integer pagenum, Integer lines) {
        pagenum = (pagenum - 1) * lines;
        HashMap<String,Object> map = new HashMap<>();
        map.put("bookid",bookid);
        map.put("uid",uid);
        map.put("pagenum",pagenum);
        map.put("lines",lines);
        return commentDao.findByid(map);
    }

    /**
     *  查找多少条 ：
     *         1. 先去redis 查找 ： 有 返回
     *         2. 没有 去 数据库 查找
     * @return size
     * */
    @Override
    public int total(Integer bookid, Integer uid) {
        Long size =
                redisTemplate.boundListOps("t_comment:" + bookid).size();
        if(size.intValue() >= 1)
            return size.intValue();
        HashMap<String,Object> map = new HashMap<>();
        map.put("bookid",bookid);
//        map.put("uid",uid);
        return commentDao.total(map);
    }
}
